const express = require('express')
const app = express()

const dirPath = 'D:\\temp'
const pathPrefix = '/temp'

const multer = require('multer')
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, dirPath)
  },
  filename: (req, file, cb) => {
    let uniqueSuffix = Date.now().toString()
    let originalname = file.originalname
    if (originalname) {
      originalname = Buffer.from(originalname, 'latin1').toString('utf8')
      uniqueSuffix += ' ' + originalname
    }
    cb(null, uniqueSuffix)
  }
})
const upload = multer({ storage: storage })

/**
 * multipart/form-data
 *
 * http://127.0.0.1/api/post
 *  ● name  张智琦
 *  ● age   18
 */
app.post('/api/post', upload.none(), (req, res) => {
  console.log(req.body)
  res.send({
    status: 0,
    msg: '成功',
    data: req.body
  })
})

/**
 * 上传文件
 *
 * http://127.0.0.1/api/uploadFile
 *  ● name  张智琦
 *  ● age   18
 *  ● file  <文件>
 */
app.post('/api/uploadFile', upload.single('file'), (req, res) => {
  req.body.file = undefined
  console.log(req.body)
  console.log(req.file)
  res.send({
    status: 0,
    msg: '成功',
    data: {
      ...req.body,
      url: `http://127.0.0.1${pathPrefix}/${req.file.filename}`
    }
  })
})

/**
 * 上传多个文件
 *
 * http://127.0.0.1/api/uploadFiles
 *  ● name  张智琦
 *  ● age   18
 *  ● files <文件>
 */
app.post('/api/uploadFiles', upload.array('files', 9), (req, res) => {
  req.body.files = undefined
  console.log(req.body)
  console.log(req.files)
  const urls = req.files.map(
    elem => `http://127.0.0.1${pathPrefix}/${elem.filename}`
  )
  res.send({
    status: 0,
    msg: '成功',
    data: {
      ...req.body,
      urls
    }
  })
})

app.use(pathPrefix, express.static(dirPath))

const errorMiddleware = (err, req, res, next) => {
  res.send({
    status: 1,
    msg: err.message
  })
}
app.use(errorMiddleware)

app.listen(80, () => {
  console.log('Server running at http://127.0.0.1')
})
